package com.jiuyue.demo.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.lucene.search.TotalHits;
import org.apache.tomcat.util.codec.binary.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.mapper.SearchAsYouTypeFieldMapper;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.jiuyue.demo.Mapper.ExternalContactFollowMapper;
import com.jiuyue.demo.Mapper.ExternalContactFollowTagMapper;
import com.jiuyue.demo.Mapper.ExternalContactMapper;
import com.jiuyue.demo.entity.ExternalContact;
import com.jiuyue.demo.entity.ExternalContactFollow;
import com.jiuyue.demo.entity.ExternalContactFollowTag;
import com.jiuyue.demo.entity.ExternalUser;
import com.jiuyue.demo.es.ExtenalUserDao;
import com.jiuyue.demo.service.ElasticSearchService;

@Service
public  class ElasticSearchServiceImpl implements ElasticSearchService{

	
	@Resource
	private ExternalContactMapper externalContactMapper;
	@Resource
	private  ExternalContactFollowMapper eExternalContactFollowMapper;
	@Resource
	private ExternalContactFollowTagMapper externalContactFollowTagMapper;
	@Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
	@Resource
	private  ExtenalUserDao externalUserDao;
	@Resource
	private RestHighLevelClient restHighLevelClient;
	
	 public void deleteExternalUserById(String externalUserId,String tenantId) {
	        DeleteByQueryRequest request = new DeleteByQueryRequest();
	        // 根据多个条件 生成 boolQueryBuilder
	        request.indices("externaluser");
	        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	        boolQueryBuilder.must(QueryBuilders.matchQuery("externalContact.externalUserid", externalUserId));
	        boolQueryBuilder.must(QueryBuilders.matchQuery("externalContact.tenantId", tenantId));

	        request.setQuery(boolQueryBuilder);
	        BulkByScrollResponse bulkByScrollResponse;
	        try {
	            bulkByScrollResponse = restHighLevelClient.deleteByQuery(request, RequestOptions.DEFAULT);
	            System.out.println("总共删除"+bulkByScrollResponse.getTotal());
	        } catch (IOException exception) {
	            exception.printStackTrace();
	        }
	    }

	
		@Override
	 public void insertEs(ExternalUser esEntity) {
	        IndexRequest indexRequest = new IndexRequest("externaluser");
	        indexRequest.source(esEntity);
	        try {
	            IndexResponse index = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
	            System.out.println("================="+index);

	        } catch (IOException exception) {
	            exception.printStackTrace();
	        }

	  }
	
	
	@Override
	public String saveAllUser() {
		// 查询出所有用户
		QueryWrapper<ExternalContact> queryWrapper = new QueryWrapper<>();
		List<ExternalContact> list =   externalContactMapper.selectList(queryWrapper);
		if(list.size()!=0) {
			for (ExternalContact ex :list ) {
				ExternalUser exUser = new ExternalUser();
				exUser.setExternalContact(ex);
				//获取follow
				QueryWrapper<ExternalContactFollow> followQuery = new QueryWrapper<ExternalContactFollow>();
				followQuery.eq("external_userid",ex.getExternalUserid());
				List<ExternalContactFollow> exFollow =eExternalContactFollowMapper.selectList(followQuery);
				exUser.setExternalContactFollowList(exFollow);
				//获取tags
				QueryWrapper<ExternalContactFollowTag> tagQuery = new QueryWrapper<ExternalContactFollowTag>();
				tagQuery.eq("external_id", ex.getExternalUserid());
				List<ExternalContactFollowTag> tagList =externalContactFollowTagMapper.selectList(tagQuery);
				exUser.setExternalContactFollowTagsList(tagList);
				Gson gson = new Gson();
				//存储到es中
				//System.out.println("======="+gson.toJson(exUser));
				System.out.println(restHighLevelClient.toString());
				externalUserDao.save(exUser);	
			}
		}
		return "存储数据成功";
	}

	@Override
	public String getAllUser() {
		// TODO 自动生成的方法存根
		
        // 1. 查询索引的所有数据
        SearchRequest request = new SearchRequest();
        request.indices("externaluser");
        // 构造查询条件
        // 构造查询条件
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(QueryBuilders.matchAllQuery());

        request.source(builder);

        SearchResponse response;
		try {
			response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
			return response.toString();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}

        
		return null;
	}

	@Override
	public Object getUserByTag(){
	 //6. 组合查询
	//组装返回结果
	 List<String> userList = new ArrayList<>();
     SearchRequest request = new SearchRequest();
     request.indices("externaluser");
     SearchSourceBuilder builder = new SearchSourceBuilder();
     String[] excludes = {};
     String[] includes = {};
//   builder.fetchSource(includes, excludes);
     BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
     boolQueryBuilder.must(QueryBuilders.matchQuery("externalContactFollowList.tagIds", "etXhIaBwAA3Mxv4E20hgNuQ2hWBFIovQ"));
     boolQueryBuilder.must(QueryBuilders.matchQuery("externalContact.userid", "KeKe1Hao"));
     builder.fetchSource(includes, excludes);
    //boolQueryBuilder.mustNot(QueryBuilders.matchQuery("sex", "男"));
    //boolQueryBuilder.should(QueryBuilders.matchQuery("age", 30));
    //boolQueryBuilder.should(QueryBuilders.matchQuery("age", 40));
     builder.query(boolQueryBuilder);
     request.source(builder);
     SearchResponse response;
     Gson gson = new Gson();
	try {
		response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
		  SearchHits hits = response.getHits();
		     System.out.println(hits.getTotalHits());
		     System.out.println(response.getTook());
		     for ( SearchHit hit : hits ) {
		          System.out.println(hit.getSourceAsString());
		          String source =hit.getSourceAsString();
		          userList.add(source);     
		      }	
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	System.out.println(userList);
	return userList.toString();
	}
	

	public Object findUserByTag(String tenantId, String userId, String tags, String beginTime, String endTime, String addWay,
			String status, Integer pageNum, Integer pageSize) {
		 if(tenantId.equals("")||userId.equals("")){
	            return "租户id或用户id不能为空,请检查参数稍后重试";
	        }
	        //组装返回结果
	        List<String> userList = new ArrayList<>();
	        SearchRequest request = new SearchRequest();
	        request.indices("externaluser");
	        SearchSourceBuilder builder = new SearchSourceBuilder();
	        String[] excludes = {};
	        String[] includes = {};
	        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	        System.out.println("====="+tenantId+userId);
	        boolQueryBuilder.must(QueryBuilders.matchQuery("externalContact.userid", userId));
	        boolQueryBuilder.must(QueryBuilders.matchQuery("externalContact.tenantId", tenantId));
	        //标签不为空
	        if(!"".equals(tags.trim())){
	        	System.out.println("标签列表");
	            boolQueryBuilder.must(QueryBuilders.matchQuery("externalContactFollowList.tagIds", "etXhIaBwAA3Mxv4E20hgNuQ2hWBFIovQ"));
	        }
	        //按照时间排序
	        if(!"".equals(beginTime.trim())&&!"".equals(endTime.trim())){
	        	System.out.println("时间范围");
	            boolQueryBuilder.must(QueryBuilders.rangeQuery("externalContactFollowList.createTime").from(beginTime).to(endTime).includeLower(true).includeUpper(true));
	        }
	        //添加渠道
	        if(!"".equals(addWay.trim())){
	        	System.out.println("添加渠道");
	            boolQueryBuilder.must(QueryBuilders.matchQuery("externalContactFollowList.addWay", addWay));
	        }
	        //客户状态
	        if(!"".equals(status.trim())){
	        	System.out.println("客户状态");
	            boolQueryBuilder.must(QueryBuilders.matchQuery("externalContactFollowList.status", status));
	        }
	        builder.fetchSource(includes, excludes);
	        builder.query(boolQueryBuilder);
	        if(pageNum==0){
	            builder.from(pageNum);
	            builder.size(pageSize);
	        }else {
	            builder.from(pageNum*pageSize);
	            builder.size(pageSize);
	        }
	        request.source(builder);
	        SearchResponse response;
	        Gson gson = new Gson();
	        try {
	            response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
	            System.out.println("=========="+response);
	            SearchHits hits = response.getHits();
	            for ( SearchHit hit : hits ) {
			          System.out.println(hit.getSourceAsString());
			          String source =hit.getSourceAsString();
			          userList.add(source);     
			      }	
	            
	        } catch (IOException e) {
	            // TODO 自动生成的 catch 块
	            e.printStackTrace();
	        }
	        System.out.println(userList);
	    	return userList.toString();
	}

	/**
	 * 插入新用户根据id
	 */
	@Override
	public Object insertUserById(int id) {
		// TODO 自动生成的方法存根
		QueryWrapper<ExternalContact> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("id", id);
		ExternalContact ex =externalContactMapper.selectOne(queryWrapper);
		deleteExternalUserById(ex.getExternalUserid(),ex.getTenantId());
		ExternalUser exUser = new ExternalUser();
		exUser.setExternalContact(ex);
		//获取follow
		QueryWrapper<ExternalContactFollow> followQuery = new QueryWrapper<ExternalContactFollow>();
		followQuery.eq("external_userid",ex.getExternalUserid());
		List<ExternalContactFollow> exFollow =eExternalContactFollowMapper.selectList(followQuery);
		exUser.setExternalContactFollowList(exFollow);
		//获取tags
		QueryWrapper<ExternalContactFollowTag> tagQuery = new QueryWrapper<ExternalContactFollowTag>();
		tagQuery.eq("external_id", ex.getExternalUserid());
		List<ExternalContactFollowTag> tagList =externalContactFollowTagMapper.selectList(tagQuery);
		exUser.setExternalContactFollowTagsList(tagList);
		Gson gson = new Gson();
		//存储到es中
		//System.out.println("======="+gson.toJson(exUser));
		System.out.println(restHighLevelClient.toString());
		externalUserDao.save(exUser);	
		return null;
	}


	@Override
	public Object delUserById(int id) {
		QueryWrapper<ExternalContact> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("id", id);
		ExternalContact ex =externalContactMapper.selectOne(queryWrapper);
		deleteExternalUserById(ex.getExternalUserid(),ex.getTenantId());
		ExternalUser exUser = new ExternalUser();
		exUser.setExternalContact(ex);
		deleteExternalUserById(ex.getExternalUserid(),ex.getTenantId());
		return null;
	}
	
	
	
	
}
